package com.hmdp.controller;


import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.service.IShopTypeService;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.LOGIN_CODE_KEY;

/**
 * <p>
 * 前端控制器
 * </p>
 */
@RestController
@RequestMapping("/shop-type")
public class ShopTypeController {
    @Resource
    private IShopTypeService typeService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 项目首页查询并添加数据库
     * @return
     */
    @GetMapping("list")
    public Result queryTypeList() {

        //1.从Redis查询数据
        String s = stringRedisTemplate.opsForValue().get(LOGIN_CODE_KEY);
        //2.判断数据是否为空 不为空返回
        if (StrUtil.isNotBlank(s)){
            List<ShopType> typeList = JSONUtil.toList(s, ShopType.class);
            return Result.ok(typeList);
        }
        //3.缓存未命中，查询数据库
        List<ShopType> typeList = typeService
                .query().orderByAsc("sort").list();
        //4.将数据存入数据库
        stringRedisTemplate.opsForValue()
                .set(LOGIN_CODE_KEY,JSONUtil.toJsonStr(typeList),3, TimeUnit.SECONDS);
        //5.返回
        return Result.ok(typeList);
    }
}
